﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using Xms.Context;
using Xms.Core;
using Xms.Core.Data;
using Xms.CRM;
using Xms.File;
using Xms.Flow;
using Xms.Identity;
using Xms.Infrastructure.Utility;
using Xms.Schema.Attribute;
using Xms.Schema.Entity;
using Xms.Schema.Extensions;
using Xms.Schema.RelationShip;
using Xms.Sdk.Abstractions;
using Xms.Sdk.Abstractions.Query;
using Xms.Sdk.Client;
using Xms.Sdk.Client.AggRoot;
using Xms.Sdk.Extensions;
using Xms.Web.Api.Models;
using Xms.Web.Framework.Context;
using Xms.Web.Framework.Controller;

namespace Xms.Web.Api
{
    /// <summary>
    /// 实体数据保存接口
    /// </summary>
    [Route("{org}/api/data/aggrootsave")]
    public class AggRootSaveController : ApiControllerBase
    {
        private readonly IEntityFinder _entityFinder;
        private readonly IAttributeFinder _attributeFinder;
        private readonly IRelationShipFinder _relationShipFinder;

        private readonly IDataCreater _dataCreater;
        private readonly IDataUpdater _dataUpdater;

        private readonly IAggCreater _aggCreater;
        private readonly IAggUpdater _aggUpdater;
        private readonly IAggFinder _aggFinder;

        private readonly IAttachmentCreater _attachmentCreater;

        private readonly IBusinessProcessFlowInstanceUpdater _businessProcessFlowInstanceUpdater;

        private readonly IDataFinder _dataFinder;
        private readonly IAppContext _appContext;
        private readonly IStudentService _istudentService;
        private readonly IIntentionStudentService _intentionStudentService;
        public AggRootSaveController(IAppContext appContext
            , IWebAppContext webAppContext
            , IEntityFinder entityFinder
            , IAttributeFinder attributeFinder
            , IRelationShipFinder relationShipFinder

            , IDataCreater dataCreater
            , IDataUpdater dataUpdater

            , IAggCreater aggCreater
            , IAggUpdater aggUpdater
            , IAggFinder aggFinder

            , IAttachmentCreater attachmentCreater

            , IBusinessProcessFlowInstanceUpdater businessProcessFlowInstanceUpdater
            , IDataFinder dataFinder

            , IStudentService istudentService
            , IIntentionStudentService intentionStudentService
            )

          
            : base(webAppContext)
        {
            _entityFinder = entityFinder;
            _attributeFinder = attributeFinder;
            _relationShipFinder = relationShipFinder;

            _dataCreater = dataCreater;
            _dataUpdater = dataUpdater;

            _aggCreater = aggCreater;
            _aggUpdater = aggUpdater;
            _aggFinder = aggFinder;

            _attachmentCreater = attachmentCreater;

            _businessProcessFlowInstanceUpdater = businessProcessFlowInstanceUpdater;
            _dataFinder = dataFinder;
            _appContext = appContext;
            _istudentService = istudentService;
            _intentionStudentService = intentionStudentService;
        }

        [Description("保存记录")]
        [HttpPost]
        public async Task<IActionResult> Post([FromForm]SaveDataModel model)
        {
            if (model.EntityId.Equals(Guid.Empty))
            {
                return NotFound();
            }
            var entityMetaData = _entityFinder.FindById(model.EntityId);
            if (entityMetaData == null)
            {
                return NotFound();
            }

            AggregateRoot aggregateRoot = new AggregateRoot();
            var attributeMetaDatas = _attributeFinder.FindByEntityId(model.EntityId);
            bool isNew = !(model.RecordId.HasValue && !model.RecordId.Value.Equals(Guid.Empty));
            var thisId = Guid.Empty;
            try
            {
                Core.Data.Entity entity = new Core.Data.Entity(entityMetaData.Name);
                entity.SetIdName(attributeMetaDatas.Find(x => x.TypeIsPrimaryKey()).Name);
                dynamic headData = JObject.Parse(model.Data);
                foreach (JProperty p in headData)
                {
                    var attr = attributeMetaDatas.Find(n => n.Name.IsCaseInsensitiveEqual(p.Name));
                    if (attr != null && p.Value != null)
                    {
                        entity.SetAttributeValue(p.Name.ToString().ToLower(), entity.WrapAttributeValue(_entityFinder, attr, p.Value.ToString()));
                    }
                }
                if (isNew)
                {
                    thisId = Guid.NewGuid();
                    if (model.RelationShipName.IsNotEmpty() && model.ReferencedRecordId.HasValue)//如果存在关联关系
                    {
                        var relationShipMetas = _relationShipFinder.FindByName(model.RelationShipName);
                        if (null != relationShipMetas && relationShipMetas.ReferencingEntityId == model.EntityId && entity.GetStringValue(relationShipMetas.ReferencingAttributeName).IsEmpty())
                        {
                            //设置当前记录关联字段的值
                            entity.SetAttributeValue(relationShipMetas.ReferencingAttributeName, new EntityReference(relationShipMetas.ReferencedEntityName, model.ReferencedRecordId.Value));
                            
                            
                            //意向学员转为正式学员或者正式学员,购买课程的同时。生成学生
                            if (entityMetaData.Name == "StudentCourseRef" && model.RelationShipName == "lk_StudentCourseRef_IntentionStudentId")
                            {
                                var intentionStudent = _intentionStudentService.FindById(model.ReferencedRecordId.Value);
                                if (intentionStudent == null)
                                {
                                    return NotFound();
                                }
                                var scRef = _dataFinder.RetrieveById(entityMetaData.Name, thisId, "", true);
                                var queryStudent = new QueryExpression("Student", _appContext.GetFeature<ICurrentUser>().UserSettings.LanguageId);
                                queryStudent.ColumnSet.AddColumn("Name");
                                queryStudent.ColumnSet.AddColumn("Sex");
                                queryStudent.ColumnSet.AddColumn("Phone");
                                queryStudent.ColumnSet.AddColumn("IntentionStudentId");
                                queryStudent.ColumnSet.AddColumn("CampusId");
                                queryStudent.Criteria.AddCondition("IntentionStudentId", ConditionOperator.Equal, intentionStudent.IntentionStudentId);
                                var setStudent = _dataFinder.Retrieve(queryStudent, true);
                                if (setStudent.Count == 0)
                                {
                                    setStudent.SetIdValue(Guid.NewGuid());
                                    setStudent.SetAttributeValue("IntentionStudentId", new EntityReference("IntentionStudent", intentionStudent.IntentionStudentId));
                                    setStudent.SetAttributeValue("Name", intentionStudent.Name);
                                    setStudent.SetAttributeValue("Sex", intentionStudent.Sex);
                                    setStudent.SetAttributeValue("Phone", intentionStudent.Phone??"");
                                    setStudent.SetAttributeValue("CampusId", new EntityReference("Campus", scRef.GetGuidValue("CampusId")));
                                    var studentId = _dataCreater.Create(setStudent, true);
                                    //将学生ID 插入到学生课程表中
                                    entity.SetAttributeValue("StudentId", new EntityReference("Student", studentId));

                                    //同时创建学生登陆账户
                                    var querySystemUser = new QueryExpression("SystemUser", _appContext.GetFeature<ICurrentUser>().UserSettings.LanguageId);
                                    querySystemUser.ColumnSet.AddColumn("Name");
                                    querySystemUser.ColumnSet.AddColumn("LoginName");
                                    querySystemUser.ColumnSet.AddColumn("RealName");
                                    querySystemUser.ColumnSet.AddColumn("password");
                                    querySystemUser.ColumnSet.AddColumn("StudentId");
                                    querySystemUser.ColumnSet.AddColumn("JobId");
                                    querySystemUser.Criteria.AddCondition("StudentId", ConditionOperator.Equal, studentId);
                                    var setSystemUser = _dataFinder.Retrieve(querySystemUser, true);
                                    if (setSystemUser.Count == 0)
                                    {
                                        setSystemUser.SetIdValue(Guid.NewGuid());
                                        setSystemUser.SetAttributeValue("Name", intentionStudent.Name);
                                        setSystemUser.SetAttributeValue("LoginName", intentionStudent.Name);
                                        setSystemUser.SetAttributeValue("RealName", intentionStudent.Name);
                                        setSystemUser.SetAttributeValue("password", "96e79218965eb72c92a549dd5a330112");//默认密码111111
                                        setSystemUser.SetAttributeValue("JobId", new EntityReference("Job", new Guid("5AA9FA3D-DDC3-4D82-AB7E-CE145A24049E"))); //职位学生
                                        setSystemUser.SetAttributeValue("StudentId", new EntityReference("Student", studentId));
                                        _dataCreater.Create(setSystemUser, true);
                                    }
                                }
                            }
                        }
                    }
                    if (!model.StageId.Equals(Guid.Empty))//业务流程的阶段
                    {
                        entity.SetAttributeValue("StageId", model.StageId);
                    }
                    //thisId = _dataCreater.Create(entity);
                    if (!model.StageId.Equals(Guid.Empty))//业务流程的阶段
                    {
                        _businessProcessFlowInstanceUpdater.UpdateForward(model.BusinessFlowId, model.BusinessFlowInstanceId, model.StageId, thisId);
                    }
                }
                else
                {
                    thisId = model.RecordId.Value;
                    entity.SetIdValue(model.RecordId.Value);
                }
                aggregateRoot.MainEntity = entity;
                aggregateRoot.ChildEntities = new List<RefEntity>();
                //单据体
                if (model.Child.IsNotEmpty())
                {
                    var childs = JArray.Parse(model.Child.UrlDecode());
                    if (childs.Count > 0)
                    {
                        List<Core.Data.Entity> childEntities = new List<Core.Data.Entity>();
                        List<string> entityNames = new List<string>();
                        foreach (var c in childs)
                        {
                            dynamic root = JObject.Parse(c.ToString());
                            string name = root.name, relationshipname = root.relationshipname, refname = string.Empty;
                            OperationTypeEnum? entitystatus = root.entitystatus;
                            if (!entityNames.Exists(n => n.IsCaseInsensitiveEqual(name)))
                            {
                                entityNames.Add(name);
                            }

                            var data = root.data;
                            var childAttributes = _attributeFinder.FindByEntityName(name);
                            if (relationshipname.IsNotEmpty())
                            {
                                var relationShipMetas = _relationShipFinder.FindByName(relationshipname);
                                if (null != relationShipMetas && relationShipMetas.ReferencedEntityId == model.EntityId)
                                {
                                    refname = relationShipMetas.ReferencingAttributeName;
                                }
                            }
                            Core.Data.Entity detail = new Core.Data.Entity(name);
                            RefEntity refEntity = new RefEntity()
                            {
                                Name = name,
                                Relationshipname = relationshipname,
                                Entityid = model.EntityId,
                                Entitystatus = entitystatus
                            };

                            foreach (JProperty p in data)
                            {
                                var attr = childAttributes.Find(n => n.Name.IsCaseInsensitiveEqual(p.Name));
                                if (attr != null && p.Value != null)
                                {
                                    detail.SetAttributeValue(p.Name.ToString().ToLower(), detail.WrapAttributeValue(_entityFinder, attr, p.Value.ToString()));
                                }
                                refEntity.Entity = detail;
                            }
                            //关联主记录ID
                            if (refname.IsNotEmpty())
                            {
                                detail.SetAttributeValue(refname, new EntityReference(entityMetaData.Name, thisId));
                            }
                            aggregateRoot.ChildEntities.Add(refEntity);
                        }
                    }
                }

                //附件保存
                var files = Request.Form.Files;
                if (files.Count > 0)
                {
                    var result = await _attachmentCreater.CreateManyAsync(model.EntityId, thisId, files.ToList()).ConfigureAwait(false);
                    for (int i = 0; i < files.Count; i++)
                    {
                        var attr = attributeMetaDatas.Find(n => n.Name.IsCaseInsensitiveEqual(files[i].Name));
                        if (attr != null)
                        {
                            var etAttachement = result.Where(x => x["Name"].ToString().IsCaseInsensitiveEqual(files[i].FileName)).First();
                            if (etAttachement != null)
                            {
                                entity.SetAttributeValue(files[i].Name, entity.WrapAttributeValue(_entityFinder, attr, etAttachement["CDNPath"].ToString()));
                            }
                        }
                    }
                }

                if (isNew)
                {
                    thisId = _aggCreater.Create(aggregateRoot, thisId, model.FormId);
                }
                else
                {
                    _aggUpdater.Update(aggregateRoot, model.FormId);
                }

                //如果是进货、退货、调拨、报损、领用、退领，需要去计算合计金额及物品库存
                if (new string[] { "GoodsPurchase", "GoodsReturnPurchase", "GoodsAllocation", "GoodsFrmLoss", "GoodsUse", "GoodsRefund" }.Contains(entityMetaData.Name))
                {
                    if (aggregateRoot.ChildEntities != null && aggregateRoot.ChildEntities.Count > 0)
                    {
                        //获取主表信息
                        var data = _dataFinder.RetrieveById(entityMetaData.Name, thisId, "", true);
                        //获取仓库id
                        var warehouseId = data.GetGuidValue("WarehouseId");

                        Guid? inWarehouseId = null;
                        if (entityMetaData.Name == "GoodsAllocation")
                        {
                            inWarehouseId = data.GetGuidValue("InWarehouseId");
                        }

                        var childrenEntityName = aggregateRoot.ChildEntities[0].Name;
                        var queryTeam = new QueryExpression(childrenEntityName, _appContext.GetFeature<ICurrentUser>().UserSettings.LanguageId);
                        queryTeam.ColumnSet.AddColumn("GoodsId");
                        queryTeam.ColumnSet.AddColumn("Quantity");
                        queryTeam.ColumnSet.AddColumn("TotalAmount");
                        queryTeam.Criteria.AddCondition(entityMetaData.Name + "Id", ConditionOperator.Equal, thisId);
                        var children = _dataFinder.RetrieveAll(queryTeam, true);
                        if (children != null && children.Count > 0)
                        {
                            var list = children.Select(n => new { GoodsId = n.GetGuidValue("GoodsId"), Quantity = n.GetIntValue("Quantity"), TotalAmount = n.GetDecimalValue("TotalAmount") }).ToList();
                            if (list.Count > 0)
                            {
                                //更新合计金额
                                var entityNew = new Core.Data.Entity(entityMetaData.Name);
                                entityNew.SetIdValue(thisId);
                                entityNew.SetAttributeValue("TotalAmount", list.Sum(t => t.TotalAmount));
                                _dataUpdater.Update(entityNew, true);

                                if (isNew)
                                {
                                    //更新物品库存
                                    foreach (var l in list)
                                    {
                                        var queryGoodsInventory = new QueryExpression("GoodsInventory", _appContext.GetFeature<ICurrentUser>().UserSettings.LanguageId);
                                        queryGoodsInventory.ColumnSet.AddColumn("InventoryQuantity");
                                        queryGoodsInventory.Criteria.AddCondition("WarehouseId", ConditionOperator.Equal, warehouseId);
                                        queryGoodsInventory.Criteria.AddCondition("GoodsId", ConditionOperator.Equal, l.GoodsId);
                                        var goodsInventory = _dataFinder.Retrieve(queryGoodsInventory, true);
                                        var inventoryQuantity = goodsInventory.GetIntValue("InventoryQuantity");
                                        switch (entityMetaData.Name)
                                        {
                                            case "GoodsPurchase":
                                                inventoryQuantity += l.Quantity;
                                                break;
                                            case "GoodsReturnPurchase":
                                                inventoryQuantity -= l.Quantity;
                                                break;
                                            case "GoodsAllocation":
                                                inventoryQuantity -= l.Quantity;
                                                break;
                                            case "GoodsFrmLoss":
                                                inventoryQuantity -= l.Quantity;
                                                break;
                                            case "GoodsUse":
                                                inventoryQuantity -= l.Quantity;
                                                break;
                                            case "GoodsRefund":
                                                inventoryQuantity += l.Quantity;
                                                break;
                                        }

                                        //新增当前物品库存
                                        if (goodsInventory.Count == 0)
                                        {
                                            goodsInventory.SetIdValue(Guid.NewGuid());
                                            goodsInventory.SetAttributeValue("WarehouseId", new EntityReference("Warehouse", warehouseId));
                                            goodsInventory.SetAttributeValue("GoodsId", new EntityReference("Goods", l.GoodsId));
                                            goodsInventory.SetAttributeValue("InventoryQuantity", inventoryQuantity < 0 ? 0 : inventoryQuantity);
                                            _dataCreater.Create(goodsInventory, true);
                                        }
                                        else  //修改当前物品库存
                                        {
                                            goodsInventory.SetAttributeValue("InventoryQuantity", inventoryQuantity < 0 ? 0 : inventoryQuantity);
                                            _dataUpdater.Update(goodsInventory, true);
                                        }

                                        //如果是调拨，还存在拨入仓库库存增加
                                        if (entityMetaData.Name == "GoodsAllocation" && inWarehouseId.HasValue)
                                        {
                                            var queryGoodsInventoryIn = new QueryExpression("GoodsInventory", _appContext.GetFeature<ICurrentUser>().UserSettings.LanguageId);
                                            queryGoodsInventoryIn.ColumnSet.AddColumn("InventoryQuantity");
                                            queryGoodsInventoryIn.Criteria.AddCondition("WarehouseId", ConditionOperator.Equal, inWarehouseId);
                                            queryGoodsInventoryIn.Criteria.AddCondition("GoodsId", ConditionOperator.Equal, l.GoodsId);
                                            var goodsInventoryIn = _dataFinder.Retrieve(queryGoodsInventoryIn, true);
                                            var inventoryQuantityIn = goodsInventoryIn.GetIntValue("InventoryQuantity");

                                            inventoryQuantityIn += l.Quantity;
                                            //新增当前物品库存
                                            if (goodsInventoryIn.Count == 0)
                                            {
                                                goodsInventoryIn.SetIdValue(Guid.NewGuid());
                                                goodsInventoryIn.SetAttributeValue("WarehouseId", new EntityReference("Warehouse", warehouseId));
                                                goodsInventoryIn.SetAttributeValue("GoodsId", new EntityReference("Goods", l.GoodsId));
                                                goodsInventoryIn.SetAttributeValue("InventoryQuantity", inventoryQuantity < 0 ? 0 : inventoryQuantity);
                                                _dataCreater.Create(goodsInventoryIn, true);
                                            }
                                            else  //修改当前物品库存
                                            {
                                                goodsInventoryIn.SetAttributeValue("InventoryQuantity", inventoryQuantity < 0 ? 0 : inventoryQuantity);
                                                _dataUpdater.Update(goodsInventoryIn, true);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    //进货的同时，更新物品的平均进货单价： 进货单价总和除以进货数量
                    if (entityMetaData.Name == "GoodsPurchase")
                    {
                        //获取物品id
                        var query = new QueryExpression("GoodsPurchaseDetail", _appContext.GetFeature<ICurrentUser>().UserSettings.LanguageId);
                        query.ColumnSet.AddColumn("GoodsId");
                        query.ColumnSet.AddColumn("PurchaseUnitPrice");
                        query.ColumnSet.AddColumn("Quantity");
                        query.ColumnSet.AddColumn("GoodsPurchaseId");
                        var entities = _dataFinder.RetrieveAll(query, true);
                        if (entities != null && entities.Count > 0)
                        {
                            var list = entities.Select(n => new { GoodsPurchaseId = n.GetGuidValue("GoodsPurchaseId"), GoodsId = n.GetGuidValue("GoodsId"), PurchaseUnitPrice = n.GetDecimalValue("PurchaseUnitPrice"), Quantity = n.GetIntValue("Quantity") }).ToList();
                            var needList = list.Where(e => e.GoodsPurchaseId == thisId).ToList();
                            foreach (var item in needList)
                            {
                                var goodsQuery= new QueryExpression("Goods", _appContext.GetFeature<ICurrentUser>().UserSettings.LanguageId);
                                goodsQuery.ColumnSet.AddColumn("AveragePrice");
                                goodsQuery.Criteria.AddCondition("GoodsId", ConditionOperator.Equal, item.GoodsId);
                                var entityNew = _dataFinder.Retrieve(goodsQuery, true);
                                var AveragePrice = list.Where(e => e.GoodsId == item.GoodsId).Sum(e => e.PurchaseUnitPrice * e.Quantity) / list.Where(e => e.GoodsId == item.GoodsId).Sum(e => e.Quantity);
                                entityNew.SetAttributeValue("AveragePrice", AveragePrice);
                                _dataUpdater.Update(entityNew, true);
                            }
                        }
                    }
                }
                //如果是创建学生的话，则生成相应的登陆账户
                if(isNew  && entityMetaData.Name == "Student")
                {
                    var querySystemUser = new QueryExpression("SystemUser", _appContext.GetFeature<ICurrentUser>().UserSettings.LanguageId);
                    querySystemUser.ColumnSet.AddColumn("Name");
                    querySystemUser.ColumnSet.AddColumn("LoginName");
                    querySystemUser.ColumnSet.AddColumn("RealName");
                    querySystemUser.ColumnSet.AddColumn("password");
                    querySystemUser.ColumnSet.AddColumn("StudentId");
                    querySystemUser.ColumnSet.AddColumn("JobId");
                    querySystemUser.Criteria.AddCondition("StudentId", ConditionOperator.Equal, thisId);
                    var setSystemUser = _dataFinder.Retrieve(querySystemUser, true);
                    if (setSystemUser.Count == 0)
                    {
                        var data = _dataFinder.RetrieveById(entityMetaData.Name, thisId, "", true);
                        var studentName = data.GetStringValue("Name");
                        setSystemUser.SetIdValue(Guid.NewGuid());
                        setSystemUser.SetAttributeValue("Name", studentName);
                        setSystemUser.SetAttributeValue("LoginName", studentName);
                        setSystemUser.SetAttributeValue("RealName", studentName);
                        setSystemUser.SetAttributeValue("password", "96e79218965eb72c92a549dd5a330112");//默认密码111111
                        setSystemUser.SetAttributeValue("JobId", new EntityReference("Job", new Guid("5AA9FA3D-DDC3-4D82-AB7E-CE145A24049E"))); //职位学生
                        setSystemUser.SetAttributeValue("StudentId", new EntityReference("Student", thisId));
                        _dataCreater.Create(setSystemUser, true);
                    }
                }
                //如果是排班，则根据课程课时生成相应的课表
                if (isNew && entityMetaData.Name== "ClassManager")
                {
                    var data = _dataFinder.RetrieveById(entityMetaData.Name, thisId, "", true);
                    var totalClassHour = data.GetIntValue("PlanCourse");//计划排课
                    var startTime = data.GetDateValue("PlanStartDate"); //计划开始时间
                    var weekInfos = data.GetIntValue("WeekInfos"); //周几上课
                    var campusId = data.GetGuidValue("CampusId");//校区
                    var lecturer = data.GetGuidValue("Lecturer");//授课老师
                    var courseId = data.GetGuidValue("CourseId");//课程Id
                    var classroomId = data.GetGuidValue("ClassroomId");//授课教室
                    var courseName = data.GetStringValue("CourseName");//课程名称
                    if (totalClassHour > 0)
                    {
                        var newStartTime = new DateTime();
                        var week = Convert.ToInt32(startTime.DayOfWeek);
                        if (week > weekInfos)
                        {
                            newStartTime = startTime.AddDays(7 - week + weekInfos);
                        }
                        else if (week < weekInfos)
                        {
                            newStartTime = startTime.AddDays(weekInfos-week);
                        }
                        else
                        {
                            newStartTime = startTime;
                        }
                        //多少课时则生成多少课表
                        for (int i = 0; i < totalClassHour; i++)
                        {
                            var classStartTime = newStartTime.AddDays(7*i);
                            var querySetClassIn = new QueryExpression("SetClass", _appContext.GetFeature<ICurrentUser>().UserSettings.LanguageId);
                            querySetClassIn.ColumnSet.AddColumn("CourseId");
                            querySetClassIn.ColumnSet.AddColumn("WeekInfos");
                            querySetClassIn.ColumnSet.AddColumn("CampusId");
                            querySetClassIn.ColumnSet.AddColumn("Lecturer");
                            querySetClassIn.ColumnSet.AddColumn("Name");
                            querySetClassIn.ColumnSet.AddColumn("ClassroomId");
                            querySetClassIn.ColumnSet.AddColumn("ClassManagerId");
                            querySetClassIn.ColumnSet.AddColumn("StartDateTime");                 
                            querySetClassIn.Criteria.AddCondition("ClassManagerId", ConditionOperator.Equal, thisId);
                            querySetClassIn.Criteria.AddCondition("StartDateTime", ConditionOperator.Equal, classStartTime);
                            var setClassIn = _dataFinder.Retrieve(querySetClassIn, true);
                            if (setClassIn.Count == 0)
                            {
                                setClassIn.SetIdValue(Guid.NewGuid());
                                setClassIn.SetAttributeValue("CourseId", new EntityReference("Course", courseId));
                                setClassIn.SetAttributeValue("StartDateTime", classStartTime);
                                setClassIn.SetAttributeValue("WeekInfos", weekInfos);
                                setClassIn.SetAttributeValue("CampusId", new EntityReference("Campus", campusId));
                                setClassIn.SetAttributeValue("ClassroomId", new EntityReference("Classroom", classroomId));
                                setClassIn.SetAttributeValue("Lecturer", new EntityReference("Staff", lecturer));
                                setClassIn.SetAttributeValue("Name", courseName);
                                setClassIn.SetAttributeValue("ClassManagerId", new EntityReference("ClassManager", thisId));
                                _dataCreater.Create(setClassIn, true);
                            }
                            //else
                            //{
                            //    setClassIn.SetAttributeValue("CampusClassTimeId", new EntityReference("CampusClassTime", campusClassTimeId));
                            //    setClassIn.SetAttributeValue("WeekInfos", weekInfos);
                            //    setClassIn.SetAttributeValue("CampusId", new EntityReference("Campus", campusId));
                            //    setClassIn.SetAttributeValue("Lecturer", new EntityReference("Staff", lecturer));
                            //    setClassIn.SetAttributeValue("Name", name);
                            //    setClassIn.SetAttributeValue("CampusClassId", new EntityReference("CampusClass", campusClassId));
                            //    _dataUpdater.Update(setClassIn, true);
                            //}
                        }
                    }
                }
                //如果是学生进行排班，则生成学生课表,并且修改学生购买课程数据为已排班
                if (entityMetaData.Name == "ClassManager"&&model.FormId==new Guid("d07b9154-0f36-48d0-bae7-342f490c1f3c"))
                {
                    //学生班级关系表 (班级下的所有已购买课程的学生)
                    var queryStudentClassManagerRef = new QueryExpression("StudentClassManagerRef", _appContext.GetFeature<ICurrentUser>().UserSettings.LanguageId);
                    queryStudentClassManagerRef.ColumnSet.AddColumn("StudentClassManagerRefId");
                    queryStudentClassManagerRef.ColumnSet.AddColumn("StudentId");
                    queryStudentClassManagerRef.ColumnSet.AddColumn("StudentCourseRefId");
                    queryStudentClassManagerRef.Criteria.AddCondition("ClassManagerId", ConditionOperator.Equal, thisId);
                    var children = _dataFinder.RetrieveAll(queryStudentClassManagerRef, true);
                    //获取班级下的所有课表
                    var querySetClass=new QueryExpression("SetClass", _appContext.GetFeature<ICurrentUser>().UserSettings.LanguageId);
                    querySetClass.ColumnSet.AddColumn("ClassManagerId");
                    querySetClass.ColumnSet.AddColumn("SetClassId");
                    querySetClass.Criteria.AddCondition("ClassManagerId", ConditionOperator.Equal, thisId);
                    var setClassChild = _dataFinder.RetrieveAll(querySetClass, true);
                    if (children!=null&& children.Count > 0)
                    {
                        foreach (var item in children)
                        {
                            //学生购买课程表
                            var queryStudentCourseRef = new QueryExpression("StudentCourseRef", _appContext.GetFeature<ICurrentUser>().UserSettings.LanguageId);
                            queryStudentCourseRef.ColumnSet.AddColumn("StudentId");
                            queryStudentCourseRef.Criteria.AddCondition("StudentCourseRefId", ConditionOperator.Equal, item.GetGuidValue("StudentCourseRefId"));
                            var studentCourseRef = _dataFinder.Retrieve(queryStudentCourseRef,true);
                            //更新学生班级关系表中的学生字段
                            var studentId = studentCourseRef.GetGuidValue("StudentId");
                            var scmrEntidy = new Entity("StudentClassManagerRef");
                            scmrEntidy.SetIdValue(item.GetGuidValue("StudentClassManagerRefId"));
                            scmrEntidy.SetAttributeValue("StudentId", new EntityReference("Student", studentId));
                            _dataUpdater.Update(scmrEntidy, true);
                            //更新学生购买课程表 已排班字段
                            var scrEntidy = new Entity("StudentCourseRef");
                            scrEntidy.SetIdValue(item.GetGuidValue("StudentCourseRefId"));
                            scrEntidy.SetAttributeValue("IsSetClass", 1);
                            _dataUpdater.Update(scrEntidy, true);

                            if (setClassChild != null && setClassChild.Count > 0)
                            {
                                foreach (var item2 in setClassChild)
                                {
                                    //if(!setClassChild.Exists(e=>e.GetGuidValue("StudentId")==studentId&&e.GetGuidValue("SetClassId")== item2.GetIdValue()))
                                    //{
                                    //    //为学生生成学生课表
                                    //    var setClassIn = new Entity("StudentSetClassRef");
                                    //    setClassIn.SetIdValue(Guid.NewGuid());
                                    //    setClassIn.SetAttributeValue("StudentId", new EntityReference("Student", studentId));
                                    //    setClassIn.SetAttributeValue("SetClassId", new EntityReference("SetClass", item2.GetIdValue()));
                                    //    _dataCreater.Create(setClassIn, true);
                                    //}
                                    //为学生生成学生课表
                                    var queryStudentSetClassRef = new QueryExpression("StudentSetClassRef", _appContext.GetFeature<ICurrentUser>().UserSettings.LanguageId);
                                    queryStudentSetClassRef.ColumnSet.AddColumn("StudentId");
                                    queryStudentSetClassRef.ColumnSet.AddColumn("SetClassId");
                                    queryStudentSetClassRef.ColumnSet.AddColumn("StudentCourseRefId");
                                    queryStudentSetClassRef.Criteria.AddCondition("StudentId", ConditionOperator.Equal, studentId);
                                    queryStudentSetClassRef.Criteria.AddCondition("SetClassId", ConditionOperator.Equal, item2.GetIdValue());
                                    var setClassIn = _dataFinder.Retrieve(queryStudentSetClassRef, true);
                                    if (setClassIn.Count == 0)
                                    {
                                        setClassIn.SetIdValue(Guid.NewGuid());
                                        setClassIn.SetAttributeValue("StudentId", new EntityReference("Student", studentId));
                                        setClassIn.SetAttributeValue("StudentCourseRefId", new EntityReference("StudentCourseRef", item.GetGuidValue("StudentCourseRefId")));
                                        setClassIn.SetAttributeValue("SetClassId", new EntityReference("SetClass", item2.GetIdValue()));
                                        _dataCreater.Create(setClassIn, true);
                                    }
                                }
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                return JError(ex.InnerException != null ? ex.InnerException.Message : ex.Message);
            }
            if (isNew)
            {
                return CreateSuccess(new { id = thisId });
            }
            return UpdateSuccess(new { id = thisId });
        }
    }
}